<template>
  <div class="permission-role">
    <h1 class="page-title">角色管理页面</h1>
    <div class="table-container">
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between;">
        <el-button type="primary" @click="showAddForm">添加角色</el-button>
        <div>
          <el-input
            v-model="searchKeyword"
            placeholder="请输入角色名称或角色标识"
            style="width: 250px; margin-right: 10px;"
            clearable
            @clear="searchRoles"
            @keyup.enter="searchRoles"
          />
          <el-button type="primary" @click="searchRoles">搜索</el-button>
        </div>
      </div>
      <el-table :data="roleList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="主键ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" width="150" />
        <el-table-column prop="roleLogo" label="角色标识" width="150" />
        <el-table-column prop="roleDes" label="角色描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="setPermissions(scope.row)">
              设置权限
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="editRole(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteRole(scope.row)"
              :disabled="scope.row.status === 2">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" v-model="addDialogVisible" width="500px">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色标识" prop="roleLogo">
          <el-input v-model="addForm.roleLogo"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDes">
          <el-input v-model="addForm.roleDes" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="禁用" :value="0"></el-option>
            <el-option label="启用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="confirmAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" v-model="editDialogVisible" width="500px">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色标识" prop="roleLogo">
          <el-input v-model="editForm.roleLogo"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDes">
          <el-input v-model="editForm.roleDes" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="禁用" :value="0"></el-option>
            <el-option label="启用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置权限对话框 -->
    <el-dialog title="设置权限" v-model="permissionDialogVisible" width="600px">
      <div>
        <h3>为角色 {{ currentRole.roleName }} 设置权限</h3>
        <el-checkbox-group v-model="rolePermissions">
          <el-checkbox
            v-for="permission in permissionList"
            :key="permission.id"
            :label="permission.id"
            style="display: block; margin-bottom: 10px;">
            {{ permission.permissionName }} ({{ permission.permissionCode }})
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRolePermissions">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleListAPI, updateRoleStatusAPI, deleteRoleAPI, updateRoleAPI, addRoleAPI } from '@/apis/sys'
import { getPermissionListAPI, getRolePermissionsAPI, assignPermissionsToRoleAPI } from '@/apis/sys'

export default {
  name: 'PermissionRole',
  data() {
    return {
      roleList: [],
      allRoleList: [], // 保存所有角色数据
      searchKeyword: '', // 搜索关键词
      loading: false,
      // 权限设置相关
      permissionDialogVisible: false,
      currentRole: {
        id: null,
        roleName: ''
      },
      permissionList: [], // 所有权限列表
      rolePermissions: [], // 角色已有的权限列表
      // 添加表单相关
      addDialogVisible: false,
      addForm: {
        roleName: '',
        roleLogo: '',
        roleDes: '',
        status: 1
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleLogo: [
          { required: true, message: '请输入角色标识', trigger: 'blur' }
        ],
        roleDes: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      // 编辑表单相关
      editDialogVisible: false,
      editForm: {
        id: null,
        roleName: '',
        roleLogo: '',
        roleDes: '',
        status: 1
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleLogo: [
          { required: true, message: '请输入角色标识', trigger: 'blur' }
        ],
        roleDes: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  async mounted() {
    await this.fetchRoleList()
  },
  methods: {
    // 搜索角色
    async searchRoles() {
      if (!this.searchKeyword.trim()) {
        // 如果搜索关键词为空，则显示所有角色
        await this.fetchRoleList();
        return;
      }

      // 调用后端接口进行搜索
      this.loading = true;
      try {
        const res = await getRoleListAPI({
          roleName: this.searchKeyword.trim()
        });
        if (res.code === 0) {
          this.roleList = res.data.map(role => {
            return {
              ...role,
              createTime: role.createTime || '-',
              updateTime: role.updateTime || '-'
            }
          })
          // 同时更新完整角色列表
          this.allRoleList = [...this.roleList];
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取角色列表失败'
          })
        }
      } catch (error) {
        console.error('搜索角色失败:', error);
        this.$message({
          type: 'error',
          message: '搜索角色失败: ' + (error.msg || error.message || '未知错误')
        });
      } finally {
        this.loading = false;
      }
    },

    // 设置权限
    async setPermissions(row) {
      this.currentRole = {
        id: row.id,
        roleName: row.roleName
      }
      await this.fetchPermissionList()
      await this.fetchRolePermissions(row.id)
      this.permissionDialogVisible = true
    },

    // 获取所有权限列表
    async fetchPermissionList() {
      try {
        const res = await getPermissionListAPI({
          pageNo: 1,
          pageSize: 100 // 获取所有权限，假设不超过100个
        })
        if (res.code === 0) {
          if (res.data && res.data.records) {
            this.permissionList = res.data.records
          } else if (Array.isArray(res.data)) {
            this.permissionList = res.data
          } else {
            this.permissionList = []
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取权限列表失败'
          })
        }
      } catch (error) {
        console.error('获取权限列表失败:', error)
        this.$message({
          type: 'error',
          message: '获取权限列表失败: ' + (error.msg || error.message || '未知错误')
        })
      }
    },

    // 获取角色已有的权限
    async fetchRolePermissions(roleId) {
      try {
        const res = await getRolePermissionsAPI(roleId)
        if (res.code === 0) {
          // 假设返回的数据是权限ID数组
          if (Array.isArray(res.data)) {
            this.rolePermissions = res.data
          } else {
            this.rolePermissions = []
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取角色权限失败'
          })
        }
      } catch (error) {
        console.error('获取角色权限失败:', error)
        this.$message({
          type: 'error',
          message: '获取角色权限失败: ' + (error.msg || error.message || '未知错误')
        })
      }
    },

    // 保存角色权限设置
    async saveRolePermissions() {
      try {
        const requestData = {
          roleId: this.currentRole.id,
          permissionIds: this.rolePermissions
        }

        const res = await assignPermissionsToRoleAPI(requestData)
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '权限设置保存成功!'
          })
          this.permissionDialogVisible = false
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '保存角色权限失败'
          })
        }
      } catch (error) {
        console.error('保存角色权限失败:', error)
        this.$message({
          type: 'error',
          message: '保存角色权限失败: ' + (error.msg || error.message || '未知错误')
        })
      }
    },

    async fetchRoleList() {
      this.loading = true
      try {
        const res = await getRoleListAPI()
        if (res.code === 0) {
          const formattedRoles = res.data.map(role => {
            return {
              ...role,
              createTime: role.createTime || '-',
              updateTime: role.updateTime || '-'
            }
          })
          this.allRoleList = formattedRoles
          this.roleList = [...formattedRoles]
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取角色列表失败'
          })
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
        this.$message({
          type: 'error',
          message: '获取角色列表失败: ' + (error.msg || error.message || '未知错误')
        })
      } finally {
        this.loading = false
      }
    },
    // 显示添加表单
    showAddForm() {
      // 重置表单数据
      this.addForm = {
        roleName: '',
        roleLogo: '',
        roleDes: '',
        status: 1
      }
      this.addDialogVisible = true
    },
    // 取消添加
    cancelAdd() {
      this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    // 确认添加
    confirmAdd() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 调用API添加角色
            const res = await addRoleAPI(this.addForm)

            if (res.code === 0) {
              // 添加成功后重新获取完整角色列表
              await this.fetchRoleList()

              this.$message({
                type: 'success',
                message: '角色添加成功!'
              })
              this.addDialogVisible = false
            } else {
              this.$message({
                type: 'error',
                message: res.msg || '角色添加失败'
              })
            }
          } catch (error) {
            console.error('添加角色失败:', error)
            this.$message({
              type: 'error',
              message: '添加角色失败: ' + (error.msg || error.message || '未知错误')
            })
          }
        }
      })
    },
    getStatusType(status) {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'info'
        default:
          return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 0:
          return '禁用'
        case 1:
          return '启用'
        case 2:
          return '删除'
        default:
          return '未知'
      }
    },
    // 编辑角色
    editRole(row) {
      this.editForm = {
        id: row.id,
        roleName: row.roleName,
        roleLogo: row.roleLogo,
        roleDes: row.roleDes,
        status: row.status
      }
      this.editDialogVisible = true
    },
    // 确认编辑
    confirmEdit() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 调用API更新角色信息
            const res = await updateRoleAPI(this.editForm)

            if (res.code === 0) {
              // 更新成功后重新获取角色列表
              await this.fetchRoleList()

              this.$message({
                type: 'success',
                message: '角色更新成功!'
              })
              this.editDialogVisible = false
            } else {
              this.$message({
                type: 'error',
                message: res.msg || '角色更新失败'
              })
            }
          } catch (error) {
            console.error('更新角色失败:', error)
            this.$message({
              type: 'error',
              message: '更新角色失败: ' + (error.msg || error.message || '未知错误')
            })
          }
        }
      })
    },
    async toggleStatus(row) {
      try {
        // 准备请求数据
        const requestData = {
          id: row.id,
          status: row.status === 1 ? 0 : 1
        };

        // 调用API更新状态
        const res = await updateRoleStatusAPI(requestData);

        if (res.code === 0) {
          // 更新成功后重新获取角色列表
          await this.fetchRoleList();

          this.$message({
            type: 'success',
            message: '状态更新成功!'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '状态更新失败'
          });
        }
      } catch (error) {
        console.error('状态更新失败:', error);
        this.$message({
          type: 'error',
          message: '状态更新失败: ' + (error.msg || error.message || '未知错误')
        });
      }
    },
    async deleteRole(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 准备请求数据
          const requestData = {
            id: row.id
          };

          // 调用API删除角色
          const res = await deleteRoleAPI(requestData);

          if (res.code === 0) {
            // 删除成功后重新获取角色列表
            await this.fetchRoleList();

            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.msg || '删除失败'
            });
          }
        } catch (error) {
          console.error('删除失败:', error);
          this.$message({
            type: 'error',
            message: '删除失败: ' + (error.msg || error.message || '未知错误')
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    formatCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  },
}
</script>

<style scoped>
.permission-role {
  padding: 20px;
  background-color: #f5f5f5;
  text-align: center;
}

.page-title {
  font-size: 2.2rem;
  color: #2c3e50;
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  text-align: left;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 1.8rem;
  }
}
</style>